//
//  AddTipContentViewController.m
//  TipsProject
//
//  Created by Suny on 15/5/20.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "AddTipContentViewController.h"
#import "MGScrollView.h"
#import "MGTableBoxStyled.h"
#import "TipItemView.h"
#import "UIBarButtonItem+BaseFramework.h"
#import "TipItem.h"
#import "MLSelectPhotoPickerViewController.h"
#import "MLSelectPhotoAssets.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "AddTipTextViewController.h"
#import "TipInfo.h"
#import "TipImageItem.h"
#import "TipTextItem.h"
#import "TopicView.h"
#import "TipInfoDetailViewController.h"
#import "UserInfo.h"

#import "AddTitpTittleViewController.h"

#define kColumCountPerRow 3
#define kItemInterval 8

//#define IPHONE_PORTRAIT_PHOTO  (CGSize){(self.view.frame.size.width-(kColumCountPerRow + 1)*kItemInterval)/kColumCountPerRow, 105}
#define IPHONE_PORTRAIT_PHOTO  (CGSize){83, 105}


#define IPHONE_PORTRAIT_GRID   (CGSize){self.scroller.frame.size.width, 0}

@interface AddTipContentViewController()
{
    UIImage *arrow;
    ActionSheet *editPhotoActionSheet;
}
@property (nonatomic, strong) TipInfo *tipInfo;
@property (nonatomic, strong) MGBox *photosGrid;
@property (nonatomic, strong) NSMutableArray *tipItemArray;

@property (nonatomic,strong) TopicView *topicView;
@end
@implementation AddTipContentViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        self.hasNavigationBar = YES;
    }
    return self;
}


- (NSMutableArray *)tipItemArray
{
	if (!_tipItemArray)
	{
		_tipItemArray = [NSMutableArray array];
	}
	return _tipItemArray;
}
- (MGScrollView *)scroller
{
    if (!_scroller)
    {
        _scroller = [MGScrollView scroller];
    }

    return _scroller;
}




- (TipInfo *)tipInfo
{
	if (!_tipInfo)
	{
		_tipInfo = [[TipInfo alloc]init];
		_tipInfo.memberPhoto = [LoginUserInfo sharedInstance].headPhoto;
		_tipInfo.memberNickName = [LoginUserInfo sharedInstance].nickName;
	}
	
	return _tipInfo;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	self.navigationItem.leftBarButtonItem =  [UIBarButtonItem leftBarButtonItemWithImageName:@"navigationbar_back_icon"
																				  target:self
																				selector:@selector(handleCancel)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"预览"
                                                                                   target:self
                                                                                 selector:@selector(handlePreviewClick)];
	
	UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.navigationBarHeight, 200, 30)];
	tipLabel.backgroundColor = [UIColor clearColor];
	tipLabel.text = @"点击添加或编辑";
	tipLabel.textAlignment = NSTextAlignmentCenter;
	tipLabel.textColor = [UIColor colorWithHexString:@""];
	tipLabel.centerX = self.view.width /2.0;
	tipLabel.font = [UIFont systemFontOfSize:18];
	[self.view addSubview:tipLabel];
	
    self.scroller.frame = CGRectMake((self.view.width - 83 * 3 - 8 * 4) /2,
									 self.navigationBarHeight + 30,
									 83 * 3 + 8*4,
									 self.view.height - self.navigationBarHeight - 30);
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"add_tip_content_background"]];
	self.scroller.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"add_tip_content_background"]];

    [self.view addSubview:self.scroller];
	
	[self setNavigationTitle:@"添加技巧"];

    // i'll be using this a lot
    arrow = [UIImage imageNamed:@"arrow"];

    // setup the main scroller (using a grid layout)
    self.scroller.contentLayoutMode = MGLayoutStackHorizontalWithWrap;
    self.scroller.bottomPadding = 8;

    // iPhone or iPad grid?
    CGSize photosGridSize = IPHONE_PORTRAIT_GRID;

    // the photos grid
    _photosGrid = [MGBox boxWithSize:photosGridSize];
	_photosGrid.backgroundColor = [UIColor clearColor];
    _photosGrid.contentLayoutMode = MGLayoutStackHorizontalWithWrap;

    [self.scroller.boxes addObject:_photosGrid];
    [_photosGrid layout];

    _topicView = [TopicView topicViewWithTopic:self.topicInfo
											   widthSize:[self photoBoxSize]];
    [_photosGrid.boxes addObject:_topicView];
	_topicView.title = self.tipTitle;

    WEAKSELF
	_topicView.onTap = ^{
        STRONGSELF
        AddTitpTittleViewController *editTitleViewController = [[AddTitpTittleViewController alloc] init];
        editTitleViewController.hasNavigationBar = YES;

        editTitleViewController.editText = strongSelf.tipTitle;
        editTitleViewController.finishBlock = ^(NSString * text){
            
            if (CHECK_VALID_STRING(text))
            {
                weakSelf.tipTitle = text;
                weakSelf.topicView.title = text;
                return YES;
            }
            else
            {
                return NO;
            }
            
        } ;

        [strongSelf.navigationController pushViewController:editTitleViewController  animated:YES];
	};

    // add a blank "add photo" box
    [_photosGrid.boxes addObject:self.photoAddBox];


}

- (void)handlePreviewClick
{
    TipInfoDetailViewController *tipInfoDetailViewController = [[TipInfoDetailViewController alloc] init];
	self.tipInfo.categoryId = self.topicInfo.topicId;
	self.tipInfo.title = self.tipTitle;
    tipInfoDetailViewController.previewMode = YES;
	tipInfoDetailViewController.tipInfo = self.tipInfo;
	self.tipInfo.fileArray = self.tipItemArray;
    [self.navigationController pushViewController:tipInfoDetailViewController
                                         animated:YES];
}

- (void)handleCancel
{
	[self.navigationController dismissViewControllerAnimated:YES completion:^{
		
	}];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self willAnimateRotationToInterfaceOrientation:self.interfaceOrientation
                                           duration:1];
    [self didRotateFromInterfaceOrientation:UIInterfaceOrientationPortrait];
}

#pragma mark - Rotation and resizing

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)o {
    return NO;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orient
                                         duration:(NSTimeInterval)duration {

    // grid size
    _photosGrid.size = IPHONE_PORTRAIT_GRID;

    // photo sizes
    CGSize size = IPHONE_PORTRAIT_PHOTO;

    // apply to each photo
    for (MGBox *photo in _photosGrid.boxes) 
	{
        photo.size = size;
        photo.layer.shadowPath
                = [UIBezierPath bezierPathWithRect:photo.bounds].CGPath;
        photo.layer.shadowOpacity = 1;
    }

    // relayout the sections
    [self.scroller layoutWithSpeed:duration completion:nil];
}

#pragma mark - Photo Box factories

- (CGSize)photoBoxSize
{

    // what size plz?
    return  IPHONE_PORTRAIT_PHOTO ;
}

- (MGBox *)photoAddBox
{

    // make the box
    TipItemView *box = [TipItemView itemAddBoxWithSize:[self photoBoxSize]];

    box.leftMargin = kItemInterval;
    box.topMargin = kItemInterval;
    // deal with taps
	WEAKSELF
    box.onTap = ^{

		[weakSelf showActionSheet];

    };
	
	box.layer.shadowPath = nil;	
	// shadow
	box.layer.shadowColor = [UIColor clearColor].CGColor;
	box.layer.shadowOffset = CGSizeMake(0, 0);
	box.layer.shadowRadius = 0;
	box.layer.shadowOpacity = 0;
	box.layer.backgroundColor = [UIColor clearColor].CGColor;

    return box;
}


#pragma -
#pragma mark - IconActionSheet
- (void)showActionSheet
{
    NSArray *shareButtonTitleArray;
    NSArray *shareButtonImageNameArray;
    shareButtonTitleArray = @[@"图库",@"拍照",@"文字"];
    shareButtonImageNameArray = @[@"add_tip_item_image",@"add_tip_item_cam",@"add_tip_item_text"];


    IconActionSheet *lxActivity = [[IconActionSheet alloc] initWithTitle:@"添加页面"
                                                                delegate:self
                                                       cancelButtonTitle:@"取消"
                                                       ShareButtonTitles:shareButtonTitleArray
                                               withShareButtonImagesName:shareButtonImageNameArray];
    lxActivity.tag = 3000;
	
	lxActivity.titleLabel.backgroundColor = [UIColor colorWithHexString:@"54d0c8"];
	lxActivity.titleLabel.textColor = [UIColor whiteColor];
	
	lxActivity.backGroundView.backgroundColor = [UIColor whiteColor];
    [lxActivity showInView:self.navigationController.view];
}

- (void)showEditPhotoActionSheet:(TipItemView *)tipItemView
{
    editPhotoActionSheet = [[ActionSheet alloc]initWithTitle:@"删除此图片"];
    WEAKSELF
    [editPhotoActionSheet addButtonWithTitle:@"确定" block:^{
        STRONGSELF
        [tipItemView removeFromSuperview];
        [strongSelf.photosGrid.boxes removeObject:tipItemView];
        [strongSelf.photosGrid layout];
        [strongSelf.tipItemArray removeObject:tipItemView.tipItem];

    }];
    
    [editPhotoActionSheet setCancelButtonWithTitle:@"取消" block:^{

        
    }];
    
    [editPhotoActionSheet showInView:self.navigationController.view];
}


- (void)didClickOnImageIndex:(NSInteger *)imageIndex
{
    NSLog(@"%d",(int)imageIndex);
	switch ((int)imageIndex)
	{
		case 0:
		{
			// 创建控制器
			MLSelectPhotoPickerViewController *pickerVc = [[MLSelectPhotoPickerViewController alloc] init];
			// 默认显示相册里面的内容SavePhotos
			// 默认最多能选9张图片
			pickerVc.minCount = 5;
			pickerVc.status = PickerViewShowStatusCameraRoll;
			[pickerVc show];

            WEAKSELF
   			pickerVc.callBack = ^(NSArray *assets){
                STRONGSELF
				NSMutableArray *imageArray = [NSMutableArray array];
				
				for (MLSelectPhotoAssets *asset in assets)
				{
					
					// 判断类型来获取Image
					UIImage *image = [MLSelectPhotoPickerViewController getImageWithImageObj:asset];
					[imageArray addObject:image];
				}
                [strongSelf creatImageTipItemWithImages:imageArray];
            };
		}
			
			break;
		case 1:
		{
			// 拍照
			if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos])
            {
				UIImagePickerController *controller = [[UIImagePickerController alloc] init];
				controller.sourceType = UIImagePickerControllerSourceTypeCamera;
				if ([self isFrontCameraAvailable]) {
					controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
				}
				controller.delegate = self;
				NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
				[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
				controller.mediaTypes = mediaTypes;
				controller.delegate = self;
				[self presentViewController:controller
								   animated:YES
								 completion:^(void){
								 }];
			}
			
		}
			
			break;
		case 2:
		{
			AddTipTextViewController *tipTextViewController = [[AddTipTextViewController alloc] init];
			tipTextViewController.finishBlock = ^(NSString * text){

                if (CHECK_VALID_STRING(text))
                {
                    [self addItemWithText:text];
                    return YES;

                }
                else
                {
                    return NO;
                }
				
			} ;
		
			NavigationController *navigation = [[NavigationController alloc] initWithRootViewController:tipTextViewController];
			[self presentViewController:navigation
							   animated:YES
							 completion:^(void){
							 }];

		}
			
			break;
			
		default:
			break;
	}
	
}

- (void)addItemWithText:(NSString *)text
{
	MGBox *addView = _photosGrid.boxes.lastObject;
	[addView removeFromSuperview];
	[_photosGrid.boxes removeObject:addView];
	
	TipTextItem *tipItem = [[TipTextItem alloc] init];
	tipItem.textContent = text;
	
	[self.tipItemArray addObject:tipItem];
	
	TipItemView *tipItemView = [TipItemView tipItemViewWithTipItem:tipItem
														  withSize:[self photoBoxSize]];

    WEAKSELF
    __weak TipItemView *weakTipItemView = tipItemView;
    tipItemView.onTap = ^{

        AddTipTextViewController *addTipTextViewController = [[AddTipTextViewController alloc] init];
        addTipTextViewController.textView.text = tipItem.textContent;

        [addTipTextViewController setFinishBlock:^BOOL(NSString *text)
        {
            [weakTipItemView setText:text];
            return YES;
        }];


        [weakSelf presentViewController:addTipTextViewController
                               animated:YES
                             completion:nil];


    };
	
	[_photosGrid.boxes addObject:tipItemView];
	
	
	[_photosGrid layout];
	
	[_photosGrid.boxes addObject:addView];
	
	[self.scroller layoutWithSpeed:0.3 completion:nil];
	

}

- (void)creatImageTipItemWithImages:(NSArray *)imageArray
{
	MGBox *addView = _photosGrid.boxes.lastObject;
	[addView removeFromSuperview];
	[_photosGrid.boxes removeObject:addView];
	
	for (UIImage *image in imageArray)
	{
        TipImageItem *tipItem = [[TipImageItem alloc] init];
        tipItem.image = image;

        [self.tipItemArray addObject:tipItem];

        TipItemView *tipItemView = [TipItemView tipItemViewWithTipItem:tipItem
                                                              withSize:[self photoBoxSize]];
        
        __weak TipItemView *editTipItemView = tipItemView;
        WEAKSELF
        tipItemView.onTap = ^{
            STRONGSELF
            [strongSelf showEditPhotoActionSheet:editTipItemView];
            
        };

        [_photosGrid.boxes addObject:tipItemView];

    }

	[_photosGrid.boxes addObject:addView];

	[_photosGrid layout];

	[self.scroller layoutWithSpeed:0.1 completion:nil];

}



- (void)didClickOnCancelButton
{
    NSLog(@"didClickOnCancelButton");
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{
	[picker dismissViewControllerAnimated:YES completion:^() {
		UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
		
			[self creatImageTipItemWithImages:@[portraitImg]];

	}];
}



#pragma mark camera utility
- (BOOL) isCameraAvailable{
	return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
	return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
	return [UIImagePickerController isSourceTypeAvailable:
			UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
	return [self
			cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
	return [self
			cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
	__block BOOL result = NO;
	if ([paramMediaType length] == 0) {
		return NO;
	}
	NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
	[availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
		NSString *mediaType = (NSString *)obj;
		if ([mediaType isEqualToString:paramMediaType]){
			result = YES;
			*stop= YES;
		}
	}];
	return result;
}


@end

